# -*- coding: utf-8 -*-
# @Time    : 2018-05-29 14:23
# @Author  : Yang Feng
# @Email   : yangfeng@bbdservice.com
# @File    : Rule17_IndCredit_Enforce_3Yr.py
# @Software: PyCharm

'''eof
name:3年内个人征信强制执行校验
code:IndCredit_Enforce_3Yr
tableName:
columnName:
groups:准入>个人征信
dependencies:IC
type:常用指标
datasourceType:在线指标
description:
eof'''


import sys
import json
import datetime
import re
from dateutil.relativedelta import relativedelta
reload(sys)
sys.setdefaultencoding('utf-8')


def FormatData(tableName):
    try:
        icr = json.loads(IC[0]["icr"])[tableName]
        return icr if isinstance(icr, list) and len(icr) > 0 else [{}]
    except:
        return [{}]


def Formate(time):
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y-%m-%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y-%m-%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y-%m-%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y-%m-%d')
                except:
                    date = None
    return date


def IndCreditEnforce3Yr():
    try:
        # 强制执行记录
        icrForceExecutionList = FormatData("ICRForceExecution")
        if icrForceExecutionList == [{}]:
            return u'缺失值'
        else:
            returnList= []
            for icrForceExecution in icrForceExecutionList:
                try:
                    registerDate = icrForceExecution.get("RegisterDate")
                    registerDateFormat = datetime.datetime.strptime(Formate(registerDate), "%Y-%m-%d")
                    today = datetime.datetime.now()
                    threeYearsAgo = today - relativedelta(years=3)
                    if registerDateFormat > today:
                        returnList.append(None)
                        continue
                    if registerDateFormat > threeYearsAgo:
                        returnList.append(1)
                    else:
                        returnList.append(0)
                except:
                    returnList.append(None)
                    continue
            returnListNotNone = filter(lambda x:x is not None, returnList)
            if len(returnListNotNone) == 0:
                return u'缺失值'
            else:
                return sum(returnListNotNone)
    except:
        return u"缺失值"

result = IndCreditEnforce3Yr()